<template>
  <div class="app-container">
    <div style="margin-bottom: 55px;">
      <el-row>
        <el-card shadow="never">
          <el-row style="display: flex; align-items: center;">
            <el-col :span="19">
            </el-col>
            <el-col :span="5">
              <el-button type="primary" style="margin-left: 10px" size="small" @click="handleIssueInvoice">开票</el-button>
              <el-button style="margin-left: 10px" size="small" @click="handleRedInvoice">红字</el-button>
              <el-button style="margin-left: 10px" size="small" @click="handleReset">重置</el-button>
              <el-button type="primary" style="margin-left: 10px" size="small" @click="handleCopy">复制</el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-row>
      <el-row style="padding-top: 10px;width: 98%;padding: 20px 52px 25px;min-width: 1100px;margin: 14px auto 0;background: #fff;position: relative;" class="v-deep" >
        <el-col :span="1">
          <div class="pages-account-output-invoice-style-cube-list">
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
          </div>
        </el-col>
        <el-col :span="22" style="width:99%">
          <div class="pages-account-output-invoice-style-title">电子发票（专用发票）</div>
          <el-form ref="detailForm" v-model="detailForm" :rules="rules" label-position="left" label-width="60px" size="small">
            <el-row :gutter="10">
              <!--              <el-col :span="6">-->
              <!--                <el-form-item label="邮箱:"  prop="collectMail">-->
              <!--                  <el-input v-model="detailForm.collectMail" style="width:90%"></el-input>-->
              <!--                  <el-tooltip effect="light" placement="right" style="margin-left:3px">-->
              <!--                    <div slot="content">电子发票可选择邮箱发送及短信发送，填写<br/>对应邮箱地址或手机号码即可自动发送，若<br/>该购方在购方管理中已维护邮箱地址，则可<br/>选择此处不填，系统将向该默认邮箱发送，<br/>若填写则以填写为准。</div>-->
              <!--                    <i class="el-icon-info"></i>-->
              <!--                  </el-tooltip>-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->
              <!--              <el-col :span="6">-->
              <!--                <el-form-item label="手机号:"  prop="collectMobile">-->
              <!--                  <el-input v-model="detailForm.collectMobile"></el-input>-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->
              <el-col :span="6">
                <el-form-item label="订单号:"  prop="orderNo">
                  <el-input v-model="detailForm.orderNo"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <div class="invoice-opening-tale">
                <div class="purchase">
                  <div class="first">购买方</div>
                  <div class="second">
                    <div class="inner"><strong style="color: red; margin-right: 2px">*</strong>购买名称</div>
                    <div class="inner">纳税人识别号</div>
                    <div class="inner">地址、电话</div>
                    <div class="inner" style="border-bottom: 0px solid #b76440;">开户行及账号</div>
                  </div>
                  <div class="third">
                    <div class="inner">
                      <el-select
                        v-model="detailForm.buyerName"
                        filterable
                        remote
                        reserve-keyword
                        clearable
                        placeholder="系统默认智能抬头，请连续输入四个汉字或以上"
                        :remote-method="remoteSearchValue"
                        :loading="remoteSearchValueLoading"
                        style="width: 80%"
                        @change="handleSelectBuyer"
                      ><el-option
                        v-for="item in searchValueOptions"
                        :key="item.buyerCode"
                        :label="item.buyerName + '(' + item.buyerCode + ')' "
                        :value="item.buyerCode">
                      </el-option>
                      </el-select>
                      <el-checkbox v-model="detailForm.buyerNaturalPerson" style="margin-left:3px; color: #b76440;">自然人</el-checkbox>
                    </div>
                    <div class="inner"><el-input v-model="detailForm.buyerNumber" placeholder="请输入纳税人识别号/统一社会信用代码/身份证号码"></el-input></div>
                    <div class="inner">
                      <el-input v-model="detailForm.buyerAddress" placeholder="请输入购买方地址" style="width: 60%"></el-input>
                      <el-input v-model="detailForm.buyerTel" placeholder="请输入电话" style="width: 40%; float: right" ></el-input>
                    </div>
                    <div class="inner" style=" border: 0 solid #b76440;">
                      <el-input v-model="detailForm.buyerBank"  placeholder="请输入购买方开户行" style="width: 60%"></el-input>
                      <el-input v-model="detailForm.buyerAccount" placeholder="请输入银行账号" style="width: 40%; float: right"></el-input>
                    </div>
                  </div>
                  <div class="first" >销售方</div>
                  <div class="second" >
                    <div class="inner" ><strong style="color: red; margin-right: 2px">*</strong>销售名称</div>
                    <div class="inner" ><strong style="color: red; margin-right: 2px">*</strong>纳税人识别号</div>
                    <div class="inner" ><strong style="color: red; margin-right: 2px">*</strong>地址、电话</div>
                    <div class="inner" style="border-bottom: 0px solid #b76440;"><strong style="color: red">*</strong>开户行及账号</div>
                  </div>
                  <div class="third">
                    <div class="inner">
                      <el-input v-model="detailForm.sellerName"></el-input>
                    </div>
                    <div class="inner">
                      <el-input v-model="detailForm.sellerNumber"></el-input>
                    </div>
                    <div class="inner">
                      <el-input v-model="detailForm.sellerAddress" style="width: 60%"></el-input>
                      <el-input v-model="detailForm.sellerTel" style="width: 40%; float: right" ></el-input>
                    </div>
                    <div class="inner" style=" border: 0 solid #b76440;">
                      <el-input v-model="detailForm.sellerBank" style="width: 60%"></el-input>
                      <el-input v-model="detailForm.sellerAccount" style="width: 40%; float: right"></el-input>
                    </div>
                  </div>
                </div>
                <div  :class=" 'goods ' +   (isFullScreen ? 'full-screen': '' )">
                  <el-table
                    border
                    stripe
                    default-expand-all
                    ref="tableRef"
                    v-loading="loading"
                    :data="invoiceEntryList"
                    :header-cell-style= "{
                        'font-size': '13px !important',
                        'font-weight': '600 !important',
                        'color':'#b76440',
                        'padding': '0px 0',
                        'background-color':'#FFF',
                        'border-bottom': '1px solid #b76440',
                        textAlign: 'left',
                        'height': '30px !important'
                    }"
                    :cell-style="{ padding: '8px 10px 8px 0', textAlign: 'left' }"
                    highlight-current-row style="width: 100%;"
                    :height="!isFullScreen ? 400 : '80vh'"
                  >
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="序号" align="center" prop="index" width="50">
                      <template slot-scope="scope">{{scope.$index+1}}</template>
                    </el-table-column>
                    <el-table-column label="货物或应税劳务、服务名称" align="left" prop="productCode" width="250">
                      <template slot-scope="scope">
                        <el-input size="mini" v-model="scope.row.productName" maxlength = 0 clearable placeholder="请选择"  readonly>
                          <el-button slot="append" icon="el-icon-search" style="padding: 0 10px;" @click="openSearchProductDialogOpen(scope.$index)">
                          </el-button>
                        </el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="规格型号" align="left" prop="specificatCode" width="150">
                      <template slot-scope="scope">
                        <el-input size="mini" v-model="scope.row.specificatCode" clearable placeholder="请输入" >
                        </el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="单位" align="left" prop="unit" width="120">
                      <template slot-scope="scope">
                        <el-input size="mini" v-model="scope.row.unit" clearable placeholder="请输入" >
                        </el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="数量" align="left" prop="qty" width="140">
                      <template slot-scope="scope">
                        <el-input-number size="mini" v-model="scope.row.qty" controls-position="right" :min="1" :max="9999999" @change="changePrice(scope.$index,scope.row)" style="width: 100px;"></el-input-number>
                      </template>
                    </el-table-column>

                    <el-table-column label="单价(含税)" align="left" prop="price" width="160" >
                      <template slot-scope="scope">
                        <el-input-number size="mini" v-model="scope.row.price" :precision="8"  @change="changePrice(scope.$index,scope.row)" controls-position="right" :min="1" :max="9999999" style="width: 100px;"></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="金额(含税)" align="left" prop="amount" width="140">
                      <template slot-scope="scope">
                        {{scope.row.amount}}
                      </template>
                    </el-table-column>

                    <el-table-column label="税率" align="left" prop="taxRate"  width="140">
                      <template slot-scope="scope">
                        <el-select size="mini" clearable v-model="scope.row.taxRate" style="width:100%" @change="changeTax(scope.$index,scope.row)">
                          <el-option v-for="dict in dict.type.tax_rate" :key="dict.label" :label="dict.label"
                                     :value="parseInt(dict.value)"></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="税额" align="left" prop="tax"  width="120">
                      <template slot-scope="scope">
                        {{scope.row.tax | formatCurrency}}
                      </template>
                    </el-table-column>
                    <el-table-column label="" align="left" class-name="small-padding fixed-width" fixed="right" width="100" >
                      <template slot="header" slot-scope="scope">
                        操作
                        <el-button
                          size="mini"
                          type="text"
                          style="width: 40px"
                          @click="toggleFullScreen"
                        >({{!isFullScreen ? '全屏': '恢复'}})</el-button>
                      </template>
                      <template slot-scope="scope">
                        <el-button
                          type="text"
                          size="mini"
                          @click="deleteEntry(scope.$index)"
                          style="color: red"
                          v-if="scope.$index > 0"
                        >移除</el-button>
                        <el-divider direction="vertical" v-if="scope.$index > 0"></el-divider>
                        <el-button
                          type="text"
                          size="mini"
                          @click="addEntry()"
                        >新增</el-button>
                      </template>
                    </el-table-column>
                    <div slot="empty">
                      <svg-icon icon-class="search-none" style="font-size: 64px;" />
                      <p>暂无数据</p>
                    </div>
                  </el-table>
                </div>
                <div class="total-line-amount">
                  <div class="first">合计</div>
                  <div class="second">
                    <div><span>税额</span></div>
                    <div>￥{{detailForm.tax}}</div>
                  </div>
                  <div class="third" ><div><span>金额(不含税)</span></div><div>￥{{detailForm.withoutAmount}}</div></div>
                </div>

                <div class="total-line">
                  <div class="first" >价税合计（大写）</div>
                  <div class="second">
                    <span style="padding: 4px 11px;">{{chineseFee}}</span>
                  </div>
                  <div class="third"><div><span>(小写)</span></div>
                    <div>
                      ￥{{detailForm.fee}}
                    </div>
                  </div>
                </div>

                <div class="purchase">
                  <div class="first" >开具推送</div>
                  <div class="second" >
                    <div class="inner" >手机号码</div>
                    <div class="inner" >客户邮箱</div>
                    <div class="inner" style="height: 72px;line-height: 72px; border-bottom: 0;">抄送邮箱</div>
                  </div>
                  <div class="third">
                    <div class="inner">
                      <el-input v-model="detailForm.collectMobile"></el-input>
                    </div>
                    <div class="inner">
                      <el-input v-model="detailForm.collectMail"></el-input>
                    </div>
                    <div class="inner" style="height: 72px;line-height: 72px; border-bottom: 0;">
                      <textarea rows="2" placeholder="多个邮箱地址可使用逗号或分号隔开，最大可允许维护5个邮箱地址" v-model="detailForm.emailCarbonCopy"
                                class="ant-input invoice-remarks-textArea"
                                style="flex: 1 1 0%; height: 72px; resize: none; width: 100%;">
                      </textarea>
                    </div>
                  </div>
                  <div class="fourth">备注</div>
                  <div class="fifth" style="background: rgb(255, 255, 255);">
                    <div class="inner difference-box" _nk="x4o6122" style="display: flex; flex-direction: column;">
                      <textarea rows="4" placeholder="请输入发票备注" v-model="detailForm.invoiceRemark"
                                class="ant-input invoice-remarks-textArea"
                                style="flex: 1 1 0%; height: 30px; max-height: 9.0072e+15px; resize: none;">
                      </textarea>
                    </div></div>
                </div>
                <div class="person-info" style="display: grid; grid-template-columns: 6.11111% 27.2222% 6.11111% 25.7333% 6.11111% 27.2222%;">
                  <div class="inner">开票人：</div>
                  <div class="person-info-input" _nk="x4o612a">
                    <el-input v-model="detailForm.invoiceName"></el-input>
                  </div>
                  <div class="inner">收款人：</div>
                  <div class="person-info-input" _nk="x4o6126">
                    <el-input v-model="detailForm.collectName"></el-input>
                  </div>
                  <div class="inner">复核人：</div>
                  <div class="person-info-input" _nk="x4o6128">
                    <el-input v-model="detailForm.reviewName"></el-input>
                  </div>

                </div>
              </div>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="1">
          <div class="pages-account-output-invoice-style-cube-list" style="right: 13px; left: unset;">
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 产品查询-弹出查询 -->
    <el-dialog v-dialogDrag  :close-on-click-modal="false" title="产品查询" :visible.sync="searchProductCodeDialogOpen" width="800px" append-to-body>
      <div class="dialog_box" style="height:550px;">
        <el-form label-position="left" :model="searchProductCodeQueryParams" :inline="true"  ref="searchProductCodeQueryForm" label-width="88px" >
          <el-form-item  prop="searchProductCodeSearchValue">
            <el-input
              v-model="searchProductCodeQueryParams.searchValue"
              size="mini"
              placeholder="请输入编码或名称查询产品"
              @keyup.enter.native="handleSearchProductCodeQuery"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearchProductCodeQuery">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="searchProductCodeSelectLoading" :data="searchProductCodeList"
                  height="400"
                  @row-click="handleSearchProductCodeRowClick"
                  ref="searchProductCodeSingleTable"
                  :row-key="getSearchProductCodeListRowKey"
                  :row-style="{height:2+'px'}"
                  :header-cell-style= "{
                        'font-size': '14px !important',
                        'font-weight': '500 !important',
                        'background-color':'rgb(241 241 241 / 52%)'
                      }"
                  :cell-style="{padding:'2px 4px'}"
                  border
                  @selection-change="handleSearchProductCodeSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <!-- 数据 -->
          <el-table-column prop="productCode" label="货物及服务编码" width="180"></el-table-column>
          <el-table-column prop="productName" label="货物及服务名称" ></el-table-column>
          <el-table-column prop="remark" label="备注" width="120"></el-table-column>
        </el-table>
        <pagination
          v-show="searchProductCodeTotal>0"
          :total="searchProductCodeTotal"
          :page.sync="searchProductCodeQueryParams.pageNum"
          :limit.sync="searchProductCodeQueryParams.pageSize"
          @pagination="getSearchProductCodeList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="confirmSearchProductCode">确 定</el-button>
        <el-button size="mini"   @click="searchProductCodeCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>

</template>
<style lang="scss">
  .input_num .el-input__inner{
    padding: 0 0 0 15px !important;
    color: red;
    font-weight: 700;
  }
  .el-table .warning-row {
    background: oldlace;
  }
  .el-table .success-row {
    background: #f0f9eb;
  }
  .el-card__body, .el-main {
    padding: 5px 20px !important;
  }

  .collapse-title{
    background-color: red;
  }
  .el-collapse-item__header.is-active {
    border-bottom: 1px solid #f0f2f5 !important;
  }
  .el-collapse-item__header::before{
    content: "";
    display: block;
    width: 3px;
    height: 20px;
    position: absolute;
    background-color: #297cf0;
    left: 0px;
    top: 35px;
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
  }

  .el-collapse-item__header div{
    margin-left: 10px;
  }
  .el-form-item__label{
    margin-bottom: -12px;
  }

  .v-deep{
    .el-collapse-item__arrow {
      width: 40px;
    }
    .el-icon-arrow-right:before {
      content: "展开";
      font-size: 14px;
      font-family: 'heiti';
      color: #2295ff;
    }
    .el-collapse-item__arrow.is-active {
      transform: none;
    }
    .el-collapse-item__arrow.is-active::before {
      content: "收起";
      font-size: 14px;
      font-family: 'heiti';
      color: #2295ff;
    }
    .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
      margin-bottom: 8px;
    }
  }

  .el-descriptions__header{
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    margin-bottom: 5px !important;
    margin-top: 5px;
  }
  .el-descriptions__title::before{
    content: "";
    display: block;
    width: 3px;
    height: 20px;
    position: absolute;
    background-color: #297cf0;
    left: 0px;
    margin-top: 11px;
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
  }
  .invoice-type {
    font-size: 12px;
    font-weight: 500;
    border: 2px solid;
    padding: 2px 6px;
    color: hsl(158deg 86% 34%);
    border-radius: 4px;
  }
  .invoice-type::before,
  .invoice-type::after {
    position: absolute;
    content: '';
    width: 6px;
    height: 6px;
    background-color: #fff;
    border: 2px solid hsl(158deg 86% 34%);
    border-left-color: transparent;
    border-bottom-color: transparent;
    border-radius: 50%;
    margin-top: 10px;
  }

  .invoice-type::before {
    margin-left: -10px;
    transform: rotate(45deg);
  }

  .invoice-type::after {
    margin-left: 3px;
    transform: rotate(-135deg);
  }

  // 发票样式
  .pages-account-output-invoice-style-title {
    font-size: 26px;
    font-family: STKaitiSC-Black, STKaitiSC;
    font-weight: 500;
    color: #b76440;
    text-align: center;
    letter-spacing: 15px;
    margin-bottom: 8px;
  }

  .invoice-opening-tale {
    border: 1px solid #b76440;
    overflow: hidden;
    color: #3c3c3c;
    background: rgba(255, 249, 245, .55);
  }
  .invoice-opening-tale .purchase {
    overflow: hidden;
    font-size: 14px;
    border-bottom: 1px solid #b76440;
  }
  .invoice-opening-tale .purchase .first {
    width: 6.13%;
    height: 144px;
    line-height: 144px;
    text-align: center;
    color: #b76440;
    font-family: PingFangSC-Regular, PingFang SC;
  }

  .invoice-opening-tale .purchase>div .inner {
    border-bottom: 1px solid #b76440;
    height: 36px;
    line-height: 36px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #b76440;
    font-family: PingFangSC-Regular, PingFang SC;
  }

  .invoice-opening-tale .purchase .second {
    width: 9.9%;
  }
  .invoice-opening-tale .purchase .second .inner {
    padding: 0 11px;
  }
  .invoice-opening-tale .purchase>div.second .inner {
    border-bottom: 1px solid #b76440;
    text-align: justify;
    /*text-align-last: justify;*/
    text-justify: distribute-all-lines;
  }

  .invoice-opening-tale .purchase .third {
    width: 33.9%;
  }
  .invoice-opening-tale .purchase>div {
    border-right: 1px solid #b76440;
    float: left;
    overflow: hidden;
  }
  .invoice-opening-tale .purchase .fourth {
    width: 6.13%;
    height: 144px;
    line-height: 144px;
    text-align: center;
    color: #b76440;
    font-family: PingFangSC-Regular, PingFang SC;
  }
  .invoice-opening-tale .purchase>div:last-child {
    border-right: 0 solid #d9d9d9;
  }
  .invoice-opening-tale .purchase .fifth {
    background: #f9f9f9;
    width: 43.8%;
    height: 144px;
  }
  .invoice-opening-tale .purchase .fifth .fifth-inner {
    width: 100%;
    height: 100%;
    text-align: center;
    line-height: 144px;
    font-size: 16px;
    color: #afaeae;
    background: linear-gradient(to top right, rgba(255, 249, 245, .55) 0, rgba(255, 249, 245, .55) calc(50% - 1px), #efefef 50%, rgba(255, 249, 245, .55) calc(50% + 1px), rgba(255, 249, 245, .55)), linear-gradient(to bottom right, rgba(255, 249, 245, .55) 0, rgba(255, 249, 245, .55) calc(50% - 1px), #efefef 50%, rgba(255, 249, 245, .55) calc(50% + 1px), rgba(255, 249, 245, .55));
  }

  .pages-account-output-invoice-style-cube-list {
    width: 20px;
    height: 100%;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    -ms-flex-pack: distribute;
    justify-content: space-around;
    position: absolute;
    left: 13px;
    top: 0;
  }
  .pages-account-output-invoice-style-cube-list>span {
    display: block;
    width: 20px;
    height: 20px;
    background: #e7f0fc;
    border-radius: 50%;
  }

  .full-screen {
    border: 2px solid #b76440;
    padding: 10px;
    position: fixed;
    top: 10%;
    left: 15%;
    width: 80vw;
    height: 83vh;
    z-index: 10000;
    background-color: white;
    overflow: auto;
    box-shadow: 3px 3px 2px rgba(0,0,0,0.5);
  }

  .full-screen .el-table {
    width: 100%;
    height: calc(100% - 40px); /* 假设按钮高度是40px */
  }

  .invoice-opening-tale .goods {
    border-bottom: 1px solid #b76440;
    transform: scale(1);
  }


  .invoice-opening-tale .total-line-amount {
    height: 36px;
    line-height: 36px;
    font-size: 13px;
    border-bottom: 1px solid #b76440;
  }
  .invoice-opening-tale .total-line-amount .first {
    width: 14.7%;
    text-align: center;
    color: #b76440;
    font-family: PingFangSC-Regular, PingFang SC;
    font-size: 14px;
  }
  .invoice-opening-tale .total-line-amount>div {
    border-right: 1px solid #b76440;
    float: left;
  }
  .invoice-opening-tale .total-line-amount .second {
    float: right;
    width: 250px;
    border-right: 0;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-pack: justify;
    justify-content: space-between;
  }
  .invoice-opening-tale .total-line-amount .second>div:first-child {
    width: 20%;
    text-align: center;
    color: #b76440;
    font-family: PingFangSC-Regular, PingFang SC;
    font-size: 14px;
  }
  .invoice-opening-tale .total-line-amount .second>div:nth-child(2) {
    width: 80%;
  }
  .invoice-opening-tale .total-line-amount>div:last-child {
    border-right: 0 solid #b76440;
  }
  .invoice-opening-tale .total-line-amount .third {
    float: right;
    width: 300px;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-pack: justify;
    justify-content: space-between;
  }
  .invoice-opening-tale .total-line-amount .third>div:first-child {
    width: 34%;
    text-align: center;
    color: #b76440;
    font-family: PingFangSC-Regular, PingFang SC;
    font-size: 14px;
  }
  .invoice-opening-tale .total-line-amount .third>div:nth-child(2) {
    width: 66%;
  }
  .invoice-opening-tale .total-line {
    height: 36px;
    line-height: 36px;
    font-size: 13px;
    border-bottom: 1px solid #b76440;
  }
  .invoice-opening-tale .total-line .first {
    width: 14.7%;
    text-align: center;
    color: #b76440;
    font-family: PingFangSC-Regular, PingFang SC;
    font-size: 14px;
  }
  .invoice-opening-tale .total-line .second {
    width: 50.5%;
  }
  .invoice-opening-tale .total-line>div {
    border-right: 1px solid #b76440;
    float: left;
  }
  .invoice-opening-tale .total-line>div:last-child {
    border-right: 0 solid #b76440;
  }
  .invoice-opening-tale .total-line .third {
    width: 34.71%;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-pack: justify;
    justify-content: space-between;
  }
  .invoice-opening-tale .total-line>div {
    border-right: 1px solid #b76440;
    float: left;
  }
  .invoice-opening-tale .total-line .third>div:first-child {
    width: 30%;
    text-align: center;
    color: #b76440;
    font-family: PingFangSC-Regular, PingFang SC;
    font-size: 14px;
  }
  .invoice-opening-tale .total-line .third>div:nth-child(2) {
    width: 70%;
  }
  .invoice-opening-tale .purchase>div:last-child {
    border-right: 0 solid #d9d9d9;
  }
  .invoice-opening-tale .purchase>div {
    border-right: 1px solid #b76440;
    float: left;
    overflow: hidden;
  }
  .invoice-opening-tale .purchase>div .inner .ant-input {
    border: 0 solid #b76440;
    height: 30px;
    font-size: 14px;
    color: #3c3c3c;
    outline: none;
    box-shadow: none;
    font-family: "SimSun";
  }
  textarea.ant-input {
    max-width: 100%;
    height: auto;
    min-height: 32px;
    line-height: 1.5715;
    vertical-align: bottom;
    transition: all .3s, height 0s;
  }
  .person-info{
  }
  .invoice-opening-tale .person-info .inner {
    line-height: 36px;
    text-align: center;
    color: #b76440;
    font-family: PingFangSC-Regular, PingFang SC;
    font-size: 14px;
  }
  .invoice-opening-tale .purchase .fifth .inner {
    height: 145px;
  }

</style>

<script>
    import { writeInvoice } from "@/api/doc/invoice";
    import { listBuyer } from "@/api/saleconfig/buyer";
    import { listTaxcategory } from "@/api/saleconfig/taxcategory";
    import { listProduct } from "@/api/saleconfig/product";


    export default {
        name: "SettleBillDetail",
        dicts: ['invoice_type', 'collection_type', 'business_type', 'tax_rate'],
        data() {
            return {
                chineseNums : ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"],
                chineseUnits : ["元", "拾", "佰", "仟", "万", "亿"],
                chineseDecimals : ["角", "分"],
                // 远程查询条件加载
                remoteSearchValueLoading: false,
                // 购买方
                searchValueOptions:[

                ],
                detailForm:{
                    fee: 0,
                    tax: 0,
                    withoutAmount: 0,
                    sellerName: '',
                    sellerBank: '',
                    sellerAccount: '',
                    sellerAddress: '',
                    sellerTel: '',
                    collectName: '',
                },
                // 表单校验
                rules: {
                    collectMail: [
                        {
                            type: "email",
                            message: "请输入正确的邮箱地址",
                            trigger: ["blur", "change"]
                        }
                    ],
                    collectMobile: [
                        {
                            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                            message: "请输入正确的手机号码",
                            trigger: "blur"
                        }
                    ]
                },
                chineseFee : '',
                loading:false,
                invoiceEntryList:[],
                isWithout:'含税',
                invoiceOpen:false,
                options:{
                    zIndex: 99999,
                    inline: true,
                    button: true,
                    navbar: true,
                    title: true,
                    toolbar: true,
                    tooltip: true,
                    movable: true,
                    zoomable: true,
                    rotatable: true,
                    scalable: true,
                    transition: true,
                    fullscreen: false,
                    keyboard: true,
                    url: 'data-source'
                },
                isFullScreen: false,
                currentRowIdx : 0,
                /* ======================================查询条件-产品选择======================================  */
                searchProductCodes:[],
                searchProductNames:[],
                searchProduct:{},
                searchProductCodeTotal: 0,
                searchProductCodeList: [],
                searchProductCodeDialogOpen: false,
                searchProductCodeSelectLoading: false,
                searchProductCodeQueryParams: {
                    searchValue: null,
                    pageNum: 1,
                    pageSize: 20,
                },

                /* ======================================查询条件-税收分类选择======================================  */
                searchTaxCategoryCodes:[],
                searchTaxCategoryNames:[],
                searchTaxCategoryCodeTotal: 0,
                searchTaxCategoryCodeList: [],
                searchTaxCategoryCodeDialogOpen: false,
                searchTaxCategoryCodeSelectLoading: false,
                searchTaxCategoryCodeQueryParams: {
                    searchValue: null,
                    pageNum: 1,
                    pageSize: 20,
                },

            };
        },
        created() {
            this.init();
        },
        methods: {
            init() {
                // 查询默认的
                this.$store.dispatch('GetCurrentSite').then((res) => {
                    console.log(res);
                    this.detailForm = {
                        fee: 0,
                        tax: 0,
                        withoutAmount: 0,
                        sellerName: res.data.siteName,
                        sellerBank: res.data.bankName,
                        sellerNumber: res.data.taxNumber,
                        sellerAccount: res.data.accountNo,
                        sellerAddress: res.data.address,
                        sellerTel: res.data.tel,
                        collectName: res.data.receiveBy,
                    };
                });
                this.invoiceEntryList = [];
                for (var i = 0; i < 4; i++) {
                    this.addEntry();
                }
            },
            toggleFullScreen() {
                this.isFullScreen = !this.isFullScreen;
            },

            deleteEntry(idx) {
                this.invoiceEntryList.splice(idx, 1);
                // 行号重新编排
                for (let i = 0; i < this.invoiceEntryList.length; i++) {
                    this.invoiceEntryList[i].lineNo = i + 1;
                }
                // this.form.rowCount = this.invoiceEntryList.length;
            },

            addEntry() {
                // if(this.invoiceEntryList.length > 7){
                //     this.$modal.msgError(`明细数量不能超过8个!`); return;
                // }
                const item = {
                    id: null,
                    entryId: null,
                    settleId: null,
                    custId: null,
                    siteCode: null,
                    siteName: null,
                    unit: '',
                    qty: 0,
                    withoutPrice: 0,
                    withoutAmount: 0,
                    taxRate: 0,
                    tax: 0,
                    deductAmount: 0,
                    deductRate: 0,
                    withoutDiscountAmount: 0,
                    discountAmount: 0,
                    price: 0,
                    amount: 0,
                    policyCode: null,
                    policyName: null,
                    freeTaxType: null,
                    freeTaxTypeName: null,
                    taxShortName: null,
                    productCode: '',
                    productName: '',
                    specificatCode: null,
                    createTime: null
                };
                this.invoiceEntryList.push(item);
            },

            /* ※※ 查询 产品 相关方法 start ※※ */
            /** ① 弹出查询条件-产品 */
            openSearchProductDialogOpen(idx) {
                this.currentRowIdx = idx;
                this.searchProductCodeDialogOpen = true;
                // 默认查询
                this.handleSearchProductCodeQuery();
            },
            /** ② 单击行 **/
            handleSearchProductCodeRowClick(row, column, event) {
                this.$refs.searchProductCodeSingleTable.toggleRowSelection(row);
            },
            /** ③ 行KEY **/
            getSearchProductCodeListRowKey(row) {
                return row.productCode
            },
            /** ④ 选中产品 **/
            handleSearchProductCodeSelectionChange(selection) {
                if (selection) {
                    if (selection.length > 1) {
                        const item = selection.pop();
                        this.$refs.searchProductCodeSingleTable.clearSelection();
                        this.$refs.searchProductCodeSingleTable.toggleRowSelection(item);
                        this.searchProductCodes = item.productCode;
                        this.searchProductNames = item.productName;
                        this.searchProduct = item;
                    } else {
                        if (selection[0]) {
                            this.searchProductCodes = selection[0].productCode;
                            this.searchProductNames = selection[0].productName;
                            this.searchProduct = selection[0];
                        }
                    }
                } else {
                    this.$refs.table.clearSelection();
                    this.searchProductCodes = null;
                    this.searchProductNames = null;
                    this.searchProduct = {};
                }
            },
            /** ⑤ 点击查询按钮 **/
            handleSearchProductCodeQuery() {
                this.searchProductCodeQueryParams.pageNum = 1;
                this.getSearchProductCodeList();
            },
            /** ⑥ 查询 **/
            getSearchProductCodeList() {
                this.searchProductCodeSelectLoading = true;
                listProduct(this.searchProductCodeQueryParams).then(response => {
                    this.searchProductCodeList = response.rows;
                    this.searchProductCodeTotal = response.total;
                    this.searchProductCodeSelectLoading = false;
                });
            },
            /** ⑦ 点击确认查询 **/
            confirmSearchProductCode() {
                if (this.searchProductCodes) {
                    this.invoiceEntryList[this.currentRowIdx].productName = this.searchProductNames;
                    this.invoiceEntryList[this.currentRowIdx].productCode = this.searchProductCodes;
                    this.invoiceEntryList[this.currentRowIdx].unit = this.searchProduct.unit;
                    this.invoiceEntryList[this.currentRowIdx].price = this.searchProduct.price;
                    this.invoiceEntryList[this.currentRowIdx].taxRate = this.searchProduct.taxRate;
                    this.invoiceEntryList[this.currentRowIdx].specificatCode = this.searchProduct.specificatCode;
                    // 金额
                    this.invoiceEntryList[this.currentRowIdx].amount = Number(this.invoiceEntryList[this.currentRowIdx].price * this.invoiceEntryList[this.currentRowIdx].qty).toFixed(8);
                    // 税额
                    this.invoiceEntryList[this.currentRowIdx].withoutAmount = Number(this.invoiceEntryList[this.currentRowIdx].amount / ((this.invoiceEntryList[this.currentRowIdx].taxRate / 100) + 1)).toFixed(8);
                    this.invoiceEntryList[this.currentRowIdx].tax = Number(this.invoiceEntryList[this.currentRowIdx].amount - this.invoiceEntryList[this.currentRowIdx].withoutAmount).toFixed(8);
                    this.refreshSummary();
                }
                // 关闭查询弹出框
                this.searchProductCodeCancel();
            },
            /** ⑧ 点击关闭查询弹出框 **/
            searchProductCodeCancel() {
                this.searchProductCodeDialogOpen = false;
            },
            /* ※※ 查询 产品 相关方法 end ※※ */



            /* ※※ 查询 税收分类 相关方法 start ※※ */
            /** ① 弹出查询条件-公司代码 */
            openSearchTaxCategoryDialogOpen(idx) {
                this.currentRowIdx = idx;
                this.searchTaxCategoryCodeDialogOpen = true;
                // 默认查询
                this.handleSearchTaxCategoryCodeQuery();
            },
            /** ② 单击行 **/
            handleSearchTaxCategoryCodeRowClick(row, column, event) {
                this.$refs.searchTaxCategoryCodeSingleTable.toggleRowSelection(row);
            },
            /** ③ 行KEY **/
            getSearchTaxCategoryCodeListRowKey(row) {
                return row.taxCategoryCode
            },
            /** ④ 选中税收分类 **/
            handleSearchTaxCategoryCodeSelectionChange(selection) {
                if (selection) {
                    if (selection.length > 1) {
                        const item = selection.pop();
                        this.$refs.searchTaxCategoryCodeSingleTable.clearSelection();
                        this.$refs.searchTaxCategoryCodeSingleTable.toggleRowSelection(item);
                        this.searchTaxCategoryCodes = item.taxCategoryCode;
                        this.searchTaxCategoryNames = item.taxShortName;
                    } else {
                        if (selection[0]) {
                            this.searchTaxCategoryCodes = selection[0].taxCategoryCode;
                            this.searchTaxCategoryNames = selection[0].taxShortName;
                        }
                    }
                } else {
                    this.$refs.table.clearSelection();
                    this.searchTaxCategoryCodes = null;
                    this.searchTaxCategoryNames = null;
                }
            },
            /** ⑤ 点击查询按钮 **/
            handleSearchTaxCategoryCodeQuery() {
                this.searchTaxCategoryCodeQueryParams.pageNum = 1;
                this.getSearchTaxCategoryCodeList();
            },
            /** ⑥ 查询 **/
            getSearchTaxCategoryCodeList() {
                this.searchTaxCategoryCodeSelectLoading = true;
                listTaxcategory(this.searchTaxCategoryCodeQueryParams).then(response => {
                    this.searchTaxCategoryCodeList = response.rows;
                    this.searchTaxCategoryCodeTotal = response.total;
                    this.searchTaxCategoryCodeSelectLoading = false;
                });
            },
            /** ⑦ 点击确认查询 **/
            confirmSearchTaxCategoryCode() {
                if (this.searchTaxCategoryCodes) {
                    this.invoiceEntryList[this.currentRowIdx].taxShortName = this.searchTaxCategoryNames;
                    this.invoiceEntryList[this.currentRowIdx].taxCategoryCode = this.searchTaxCategoryCodes;
                }
                // 关闭查询弹出框
                this.searchTaxCategoryCodeCancel();
            },
            /** ⑧ 点击关闭查询弹出框 **/
            searchTaxCategoryCodeCancel() {
                this.searchTaxCategoryCodeDialogOpen = false;
            },
            /* ※※ 查询 公司代码 相关方法 end ※※ */

            // 计算金额
            changePrice(idx, row) {
                row.amount = Number(row.price * row.qty).toFixed(8);
                row.withoutAmount = Number(row.amount / ((row.taxRate / 100) + 1)).toFixed(8);
                row.tax = Number(row.amount - row.withoutAmount).toFixed(8);
                this.refreshSummary();
            },
            // 计算税额
            changeTax(idx, row) {
                row.withoutAmount = Number(row.amount / ((row.taxRate / 100) + 1)).toFixed(8);
                row.tax = Number(row.amount - row.withoutAmount).toFixed(8);
                this.refreshSummary();
            },

            refreshSummary() {
                let withoutAmount = 0;
                let fee = 0;
                let tax = 0;
                this.invoiceEntryList.forEach(item => {
                    if (item.productCode) {
                        withoutAmount = Number(item.withoutAmount) + withoutAmount;
                        fee = Number(item.amount) + fee;
                        tax = Number(item.tax) + tax;
                    }
                });
                this.detailForm.fee = Number(fee).toFixed(8);
                this.detailForm.tax = Number(tax).toFixed(8);
                this.detailForm.withoutAmount = Number(this.detailForm.fee - this.detailForm.tax).toFixed(8);
                this.chineseFee = this.menoyToUppercase(this.detailForm.fee);
            },

            /** 动态加载关键字查询条件 */
            remoteSearchValue(query) {
                this.remoteSearchValueLoading = true;
                let queryParams = {
                    pageNum: 1,
                    pageSize: 9999,
                    params: {},
                    searchValue: null
                };
                queryParams.searchValue = query;
                listBuyer(queryParams).then(response => {
                    this.searchValueOptions = response.rows;
                    this.remoteSearchValueLoading = false;
                });
            },
            handleSelectBuyer(val) {
                this.searchValueOptions.forEach(item => {
                    if (item.buyerCode === val) {
                        this.detailForm.buyerNumber = item.buyerNumber;
                        this.detailForm.buyerAddress = item.buyerAddress;
                        this.detailForm.buyerTel = item.buyerTel;
                        this.detailForm.buyerBank = item.buyerBank;
                        this.detailForm.buyerAccount = item.buyerAccount;
                    }
                })
            },
            // 转中文金额
            menoyToUppercase(money) {
                var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');    //汉字的数字
                var cnIntRadice = new Array('', '拾', '佰', '仟'); //基本单位
                var cnIntUnits = new Array('', '万', '亿', '兆');  //对应整数部分扩展单位
                var cnDecUnits = new Array('角', '分', '毫', '厘'); //对应小数部分单位
                var cnInteger = '整';    //整数金额时后面跟的字符
                var cnIntLast = '元';    //整数完以后的单位
                //最大处理的数字
                var maxNum = 999999999999999.9999;
                var integerNum;  //金额整数部分
                var decimalNum;  //金额小数部分
                //输出的中文金额字符串
                var chineseStr = '';
                var parts;      //分离金额后用的数组，预定义
                if (money == '') { return ''; }

                money = parseFloat(money);
                if (money >= maxNum) {
                    //超出最大处理数字
                    return '超出最大处理数字';
                }
                if (money == 0) {
                    chineseStr = cnNums[0] + cnIntLast + cnInteger;
                    return chineseStr;
                }
                //四舍五入保留两位小数,转换为字符串
                money = Math.round(money * 100).toString();
                integerNum = money.substr(0,money.length-2);
                decimalNum = money.substr(money.length-2);
                //获取整型部分转换
                if (parseInt(integerNum, 10) > 0) {
                    var zeroCount = 0;
                    var IntLen = integerNum.length;
                    for (var i = 0; i < IntLen; i++) {
                        var n = integerNum.substr(i, 1);
                        var p = IntLen - i - 1;
                        var q = p / 4;
                        var m = p % 4;
                        if (n == '0') {
                            zeroCount++;
                        } else {
                            if (zeroCount > 0) {
                                chineseStr += cnNums[0];
                            }
                            //归零
                            zeroCount = 0;
                            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
                        }
                        if (m == 0 && zeroCount < 4) {
                            chineseStr += cnIntUnits[q];
                        }
                    }
                    chineseStr += cnIntLast;
                }
                //小数部分
                if (decimalNum != '') {
                    var decLen = decimalNum.length;
                    for (var i = 0; i < decLen; i++) {
                        var n = decimalNum.substr(i, 1);
                        if (n != '0') {
                            chineseStr += cnNums[Number(n)] + cnDecUnits[i];
                        }
                    }
                }
                if (chineseStr == '') {
                    chineseStr += cnNums[0] + cnIntLast + cnInteger;
                } else if (decimalNum == '' || /^0*$/.test(decimalNum)) {
                    chineseStr += cnInteger;
                }
                return chineseStr;
            },


            /**
             * 开票按钮
             */
            handleIssueInvoice(){
                // 校验
                //指定为普通电票  01:全电发票(增值税专用发票) 02:全电发票(普通发票)
                this.detailForm.invoiceType = "01";
                this.detailForm.tsalInvoiceEntryList = this.invoiceEntryList.filter(item => {
                    return (item.productCode)
                });
                console.log("this.detailForm");
                console.log(this.detailForm);
                writeInvoice(this.detailForm).then(response => {
                    // 显示发票
                    this.$modal.msgSuccess("操作成功");
                });

                // this.$refs["detailForm"].validate(valid => {
                //     alert(valid);
                //     if (valid) {
                //
                //     }
                // });
            },

            /**
             * 红字按钮
             */
            handleRedInvoice(){

            },
            /**
             * 红字按钮
             */
            handleReset(){
                this.init();
            },
            /**
             * 红字按钮
             */
            handleCopy(){

            },
        }
    }
</script>
